<template>
    <div>
        <div>
            <el-input style="width: 200px" placeholder="填入工单名称(选填)" v-model="workNameSearch"></el-input>
            <el-select v-model="creatorSearch" filterable placeholder="选择创建人" style="width: 150px; margin: 0 5px">
                <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
            </el-select>
            <el-select v-model="recipientSearch" filterable placeholder="选择接收人" style="width: 150px; margin: 0 5px">
                <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
            </el-select>
            <el-button type="primary" @click="load(1)">查询</el-button>
            <el-button type="primary" @click="reset">重置</el-button>
        </div>
        <div style="margin: 10px 0">
            <el-button type="primary" plain @click="handleAddOrEdit">新增</el-button>
            <el-button type="danger" plain @click="handleDelBatch">批量删除</el-button>
        </div>
        <!--  整个表格，有多选框 -->
        <el-table v-loading="loading" element-loading-text="拼命加载中" :data="tableData" stripe :header-cell-style="{backgroundColor: 'aliceblue',color: '#666'}" @selection-change="handleSelectionChange">
            <!--    复选框-->
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
            <el-table-column prop="workName" label="工单名称"></el-table-column>
            <el-table-column prop="workDescription" label="工单描述"></el-table-column>
            <el-table-column prop="attachName" label="附件名称" width="140px" show-overflow-tooltip></el-table-column>
            <el-table-column prop="attachCount" label="附件个数" width="80px"></el-table-column>
            <el-table-column prop="creatorName" label="创建人"></el-table-column>
            <el-table-column prop="creatTime" label="创建时间" width="140px"></el-table-column>
            <el-table-column prop="modifierName" label="修改人"></el-table-column>
            <el-table-column prop="updateTime" label="修改时间" width="140px"></el-table-column>
            <el-table-column prop="recipientName" label="接收人"></el-table-column>
            <el-table-column prop="receiptState" label="接收状态" width="150">
                <template v-slot="scope">
                    <el-tag :type="getStatusType(scope.row.receiptState)">{{getStatusText(scope.row.receiptState)}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="receiptTime" label="接收时间" width="140"></el-table-column>
            <el-table-column prop="remark" label="备注"></el-table-column>
            <el-table-column fixed="right" label="操作" align="center" width="240px">
                <template v-slot="scope">
                    <el-button size="mini" type="primary" plain @click="handleAddOrEdit(scope.row)">修改</el-button>
                    <el-button size="mini" type="danger" plain @click="handleDel(scope.row)">删除</el-button>
                    <el-button v-if="isRecipient(scope.row)" size="mini" type="success" plain @click="handleConfirm(scope.row)">确认接收</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div style="margin: 10px 0;text-align: center">
            <el-pagination @current-change="handleCurrentChange" :current-page="pageNum" :page-size="pageSize" layout="total,prev,pager,next" :total="total">
            </el-pagination>
        </div>
        <!-- 新增表单需要弹窗包裹 -->
        <el-dialog title="编辑信息" :visible.sync="formVisible" width="40%" @close="closeDialog">
            <el-form :model="form" label-width="80px" style="padding-right: 20px" :rules="rules" ref="formRef">
                <el-form-item label="工单名称" prop="workName">
                    <el-input v-model="form.workName" placeholder="工单名称"></el-input>
                </el-form-item>
                <el-form-item label="工单描述" prop="workDescription">
                    <el-input v-model="form.workDescription" placeholder="工单描述" type="textarea"></el-input>
                </el-form-item>
                <el-form-item label="附件" prop="attachName">
                    <el-input v-model="form.attachName" placeholder="暂无附件" :readonly="true"></el-input>
                    <div style="margin: 15px;text-align: center">
                        <!-- :on-change="handleChange" -->
                        <el-upload ref="uploader" class="upload-demo" :action="this.$apiUrl+'/file/upload'" :headers="{token: user.token}" :file-list="fileList" :on-preview="handlePreview" :on-success="handleOnSuccess" :before-upload="beforeUpload" :before-remove="beforeRemoved" multiple :limit="3" :on-exceed="handleExceed">
                            <el-button size="small" type="primary">点击上传</el-button>
                            <div slot="tip" class="el-upload__tip">注意：单个附件安全范围是100MB以内</div>
                        </el-upload>
                    </div>
                </el-form-item>
                <el-form-item label="接收人" prop="recipient">
                    <el-select v-model="form.recipient" filterable placeholder="选填" :options="userOptions" value-key="value" style="width: 150px; margin: 0 5px">
                        <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="备注(可不填)" type="textarea"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="formVisible = false">取消</el-button>
                <el-button type="primary" @click="save">保存</el-button>
            </div>
        </el-dialog>
      <!-- 预览图片 -->
      <el-dialog :visible.sync="dialogVisible">
        <img width="60%" :src="dialogImageUrl">
      </el-dialog>
    </div>
</template>
    <script>
export default {
    name: 'Distribute',
    data() {
        return {
            tableData: [], //表数据
            pageNum: 1, //当前页码
            pageSize: 10, //每页数量
            workNameSearch: '',
            creatorSearch: '',
            recipientSearch: '',
            total: 0, //数据总条数
            user: JSON.parse(localStorage.getItem('userInfo') || '{}'),
            ids: [],
            loading: true,
            formVisible: false, //默认不显示新增表单弹窗
            form: {}, //弹窗表单
            rules: {
                //校验规则
                workName: [
                    {
                        required: true,
                        message: '输入工单名称，带 * 是必填项',
                        trigger: 'blur',
                    },
                ],
            },
            fileList: [],
            // 标签数组
            tagList: [
                { value: 'admin', label: '管理员' },
                { value: 'user', label: '用户' },
                { value: 'test', label: '测试员' },
            ],
            userOptions: [],
          dialogImageUrl: '', //图片预览对话框图片地址
          dialogVisible: false//图片预览对话框
        }
    },
    created() {
        this.load()
    },
    //安装
    mounted() {
        this.initUsersOptions()
    },
    computed: {},
    components: {},
    watch: {
        // 搜索过滤，监听input搜索框绑定的treeFilter
        treeFilter(val) {
            this.$refs.tree.filter(val)
            // 当搜索框键入值改变时，将该值作为入参执行树形控件的过滤事件filterNode
        },
    },
    methods: {
        reset() {
            this.workNameSearch = ''
            this.creatorSearch = ''
            this.recipientSearch = ''
            this.load()
        },
        load(pageNum) {
            if (pageNum) this.pageNum = pageNum //分页查询时自动切换到第一页
            this.$request
                .get('/distribute/findByPage', {
                    params: {
                        pageNum: this.pageNum,
                        pageSize: this.pageSize,
                        workName: this.workNameSearch,
                        creator: this.creatorSearch,
                        recipient: this.recipientSearch,
                    },
                })
                .then((res) => {
                    if (res.code === '200') {
                        if (res.data) {
                            if (res.data.records) {
                                this.tableData = res.data.records
                            } else {
                                this.tableData = res.data
                            }
                        }
                        this.total = res.data.total
                    } else {
                        this.$message.error(res.msg)
                    }
                    this.loading = false
                })
        },
        //切换页码
        handleCurrentChange(pageNum) {
            this.load(pageNum)
        },
        handleAddOrEdit(row) {
            if (row.id) {
                //编辑模式
                this.form = JSON.parse(JSON.stringify(row)) //弹窗带出来信息,浅拷贝是内存指向，深拷贝是开区域赋值
                //需要把upload组件的fileList带出来
                if (this.form.fileListJson) {
                    this.fileList = this.form.fileListJson
                } else {
                    this.fileList = []
                }
            } else {
                this.form = {} //新增数据时清空表单
                this.fileList = [] //清空上传组件
            }
            this.formVisible = true //打开弹窗
        },
        //单个删除
        handleDel(row) {
            this.$confirm(
                '确认删除《' + row.workName + '》工单吗？',
                '确认删除',
                { type: 'warning' }
            )
                .then((ok) => {
                    this.$request
                        .delete('/distribute/delete/' + row.id)
                        .then((res) => {
                            if (res.code == '200') {
                                this.$message.success('删除成功')
                            } else {
                                this.$message.error('删除失败：' + res.msg)
                            }
                            this.load(this.pageNum) //刷新表格
                        })
                })
                .catch(() => {}) //catch捕捉先不做处理
        },
        //批量删除之前--多选框，参数是选中的行对象
        handleSelectionChange(rows) {
            this.ids = rows.map((row) => row.id) //流和表达式，将行id提取出来存入数组
        },
        //批量删除
        handleDelBatch() {
            //校验：点击批量删除按钮之前，未选择多选框时提示
            if (!this.ids.length) {
                this.$message.warning('请选择需要批量删除的工单！')
                return
            }
            this.$confirm(
                '你确认批量删除[' + this.ids + ']这些工单吗？',
                '确认删除',
                { type: 'warning' }
            )
                .then((ok) => {
                    this.$request
                        .delete('/distribute/deleteBatch', { data: this.ids })
                        .then((res) => {
                            if (res.code == '200') {
                                this.$message.success('批量删除成功')
                            } else {
                                this.$message.error('批量删除失败:' + res.msg)
                            }
                            this.load(this.pageNum) //刷新表格
                        })
                })
                .catch(() => {}) //catch捕捉先不做处理
        },
        //是否是接收人,并且接收状态是未接收
        isRecipient(row) {
            return row.recipient === this.user.id && row.receiptState === 0
        },
        //确认接收
        handleConfirm(row) {
            if (this.isRecipient(row)) {
                this.form = row
                this.form.receiptState = 1
                this.form.receiptStateLast = 0
                this.sendApi()
            } else {
                this.$message.error('你不是工单接收人，请核对')
            }
        },
        //关闭弹窗后的回调方法
        closeDialog() {
            //清除rules提示信息
            this.$refs.formRef.clearValidate()
        },
        //上传文件组件，文件改变事件(添加文件ready，上传成功success/失败error，都会被调用，至少2次)
        handleChange(file, fileList) {
            if (file.status !== 'ready') return //文件未准备好是减少调用次数
        },
        //上传文件组件，文件预览
        handlePreview(file) {
            const imageExtensions = [
                'jpg',
                'jpeg',
                'png',
                'gif',
                'bmp',
                'tiff',
                'webp',
            ]
            let fileExtensionMatch = file.response.data.fileName.match(/\.([^\.]+)$/)
            let fileExtension = fileExtensionMatch ? fileExtensionMatch[1] : '' //文件扩展名
            if (imageExtensions.includes(fileExtension.toLowerCase())) {
                // this.$message.warning('预览图片功能正在开发中……')
              this.dialogImageUrl = file.response.data.fileUrl;
              this.dialogVisible = true;
            } else {
                this.$message.warning('选中的文件不是图片，暂不支持预览，你可去文件管理里下载')
            }
        },
        //上传文件组件，限制附件个数
        handleExceed(files, fileList) {
            this.$message.warning(
                `当前限制选择 3 个附件，本次选择了 ${
                    files.length
                } 个文件，共选择了 ${files.length + fileList.length} 个文件`
            )
        },
        //上传文件组件，成功后记录文件名和文件路径
        handleOnSuccess(response, file, fileList) {
          this.fileList = fileList
          //改变附件名称
          this.changeAttachName()
        },
        //改变附件名称
        changeAttachName(){
          this.form.attachName = this.fileList
              .map((file) => file.name)
              .join('，')
        },
        //上传组件，移除元素之前
        beforeRemoved(file, fileList) {
            if (file && file.status === 'success') {
                this.$confirm(`确定移除【${file.name}】吗？`)
                    .then(() => {
                      //刷新一下全局变量
                      this.fileList = fileList
                      console.log(fileList)
                      //确认移除,改变附件名称
                      this.changeAttachName()
                      return true
                    })
                    .catch(() => {
                      //取消或关闭
                      return false
                    })
            }
        },
        //上传文件之前
        beforeUpload(file) {
            let size = file.size
            let maxSize = 100 * 1024 * 1024
            if (size > maxSize) {
                return this.$confirm(
                    '当前附件【' +
                        file.name +
                        '】文件大小超出100MB安全范围，继续上传可能会出错，请确认是否继续上传？',
                    '警告提示'
                )
            }
        },
        //保存/修改
        save() {
            //校验表单
            // 根据数组form名称找到这个校验对象
            // this.$refs[formName].validate((valid) => {
            this.$refs.formRef.validate((valid) => {
                if (valid) {
                    this.form.fileList = this.fileList
                    this.sendApi()
                } else {
                    this.$message.warning('表单校验未通过')
                    return false
                }
            })
        },
        //向接口发送
        sendApi() {
            this.$request({
                //有id就是编辑
                method: this.form.id ? 'PUT' : 'POST',
                data: this.form,
                url: this.form.id ? '/distribute/update' : '/distribute/save',
            }).then((res) => {
                if (res.code === '200') {
                    //保存成功
                    this.$message.success('操作成功')
                    this.formVisible = false
                    this.load(this.pageNum)
                } else {
                    this.$message.error(res.msg) //错误信息
                    return false
                }
                //无论是否保存成功，都要把fileList清空
                this.fileList = []
            })
        },
        getStatusText(status) {
            switch (status) {
                case 0:
                    return '未接收'
                case 1:
                    return '已接收'
                case 2:
                    return '已下载但未确认接收'
                case 3:
                    return '已确认接收但未下载'
                default:
                    return '未知'
            }
        },
        getStatusType(status) {
            switch (status) {
                case 0:
                    return 'primary'
                case 1:
                    return 'success'
                case 2:
                    return 'warning'
                case 3:
                    return 'danger'
                default:
                    return 'info' // 默认没有特殊样式
            }
        },
        //初始化用户选择框
        initUsersOptions() {
            this.$request({
                method: 'GET',
                url: '/user/getSelect',
            }).then((res) => {
                if (res.code === '200') {
                    this.userOptions = res.data
                } else {
                    this.$message.error(res.msg) //错误信息
                    return false
                }
            })
        },
    },
}
</script>

<style scoped>
</style>